<?php

	/**
	*
	*    文件名：modelAbs.php
	*    创建人: 杨旭升
	*    创建时间: 2015/1/27
	*    最后修改时间: 2015/2/3
	*    文件功能概述：数据抽象层
	*
	*/
	
	//使用lib空间
	namespace lib;

	/**
	*	连接数据抽象层
	*/     
	class ModelAbs { 

		// 配置地址，端口，用户名，密码，数据库前缀
		private static $host = '127.0.0.1';
		private static $port = '3306';
		private static $userName = 'LenovoForumAdmin';
		private static $passWord = 'yxs147789';
		private static $dbName = 'lenovoforumdb';
		private static $dbPre = 'lenforum_';

		//私有成员
		private $tableName; //表名


		/**
		*	开始连接
		*/
		public static function startConn() { 
			$conn = mysql_connect(ModelAbs::$host.':'.ModelAbs::$port, 
				ModelAbs::$userName, ModelAbs::$passWord);
			if($conn) { 
				mysql_select_db(ModelAbs::$dbName);
				mysql_query("set names utf8");
			} else { 
				die('数据库异常');
			}
		}


		/**
		*	关闭连接
		*/
		public static function endConn() { 
			mysql_close();
		}


		/**
		*	处理需要and的数据
		*/
		private function doAnd($andData, $extend = '') {
			$return = '';
			foreach($andData as $name => $value) { 
				$return .= $name.$extend.$value.' AND ';
			}
			//除掉where最后多的5个字符
			$return = substr($return, 0, count($return) - 6);
			return $return;
		}


		/**
		*	构造函数
		*/
		public function __construct($modelName) { 
			$this->tableName = ModelAbs::$dbPre.$modelName;
		}


		/**
		*	根据条件查询，支持分页
		*/
		public function select($selectCols = '*', $whereCause = false, $orderBy = false, $pageNum = false, $pageSize = 10) { 
			$sql = 'SELECT '.$selectCols.' FROM '.$this->tableName;
			//使用where
			if($whereCause) {
				$sql .= ' WHERE '.$this->doAnd($whereCause);
			}
			//使用orderBy
			if($orderBy) { 
				$sql .= ' ORDER BY '.$orderBy['order'];
				$sql .= isset($orderBy['desc'])?' DESC':'';
			}
			//使用分页
			if($pageNum) { 
				$page = ' LIMIT '.($pageNum-1)*$pageSize.', '.$pageSize;
				$sql .= $page;
			}
			$result = mysql_query($sql);
			if($result) { 
				if(!mysql_num_rows($result)) { 
					return null;
				} else { 
					$return = array();
					while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
						$return[] = $row; 
					}
					return $return;
				}
			} else {
				die('数据库异常'); 
			}
		}

		/**
		*	是否含有数据
		*/
		public function contain($whereCause = false, $returnCols = '*') { 
			return $this->select($returnCols, $whereCause, false, 1, 1);
		}

		/**
		*	添加数据
		*/
		public function add($newData) {
			$sql = 'INSERT INTO '.$this->tableName.'(';
			//先把键值对拼接成字符串
			$names = implode(',', array_keys($newData));
			$values = implode(',', $newData);
			//去掉最后一个多余的逗号
			$sql .= $names.') VALUES ('.$values.')';
			return mysql_query($sql);
		}

		/**
		*	删除数据
		*/
		public function delete($whereCause) { 
			$sql = 'DELETE FROM '.$this->tableName.' WHERE '.$this->doAnd($whereCause);
			return mysql_query($sql);
		}

		/**
		*	更新数据
		*/
		public function update($newData, $whereCause) { 
			$sql = 'UPDATE '.$this->tableName.' SET '.$this->doAnd($newData, '=').' WHERE '.$this->doAnd($whereCause);
			return mysql_query($sql);
		}
	}
?>